package com.yyk.yiliao.ui.home.activity;

import android.content.Context;
import android.content.Intent;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.orhanobut.logger.Logger;

import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.base.BaseRecyclerAdapter;
import com.yyk.yiliao.base.BaseRecyclerHolder;
import com.yyk.yiliao.bean.Recommend_Info;
import com.yyk.yiliao.ui.gongyong.activity.WebViewActivity;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.OkHttp3Utlis;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.bean.HomeHomelist_Info;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.widget.diver.CustomDecoration;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 首页------搜索
 */
public class HomeSearch_Activity extends BaseActivity {

    @BindView(R.id.mSearch_int)
    EditText mSearchInt;
    @BindView(R.id.mSearch_clean)
    ImageView mSearchClean;
    @BindView(R.id.mSearch_flow)
    TagFlowLayout mSearchFlow;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.mSearch)
    LinearLayout mSearch;
    @BindView(R.id.mSearch_rv)
    RecyclerView mSearchRv;
    @BindView(R.id.mSearch_sousuo)
    TextView mSearchSousuo;
    @BindView(R.id.mSearch_rr)
    LinearLayout mSearchRr;

    @BindView(R.id.ll_center_bg)
    LinearLayout llCenterBg;
    private List<HomeHomelist_Info.DataBean> data = new ArrayList<>();
    //    private BaseRecyclerAdapter<HospitalSearch_Info.DataBean> adapter;
    private BaseRecyclerAdapter<HomeHomelist_Info.DataBean> adapter;
    private String request;


    @Override
    public int getLayoutId() {
        return R.layout.activity_homesearch;
    }

    @Override
    public void initView() {
        initToolbar();
        initTagFlowLayout();
    }

    private void initToolbar() {
        hidetoolBar();
        toolbar.setNavigationIcon(getResources().getDrawable(R.mipmap.icon_shangp_fh));
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initAdapter() {
        adapter = new BaseRecyclerAdapter<HomeHomelist_Info.DataBean>(HomeSearch_Activity.this, data, R.layout.adapter_item_hospitaldoctor) {
            @Override
            public void convert(BaseRecyclerHolder holder, HomeHomelist_Info.DataBean item, int position, boolean isScrolling) {
                if (item.getType() == 1) {
                    holder.setText(R.id.b_hospital_name, item.getTrue_name());
                } else {
                    holder.setText(R.id.b_hospital_name, item.getHospital_name());
                }
            }
        };
        mSearchRv.addItemDecoration(new CustomDecoration(mActivity, CustomDecoration.VERTICAL_LIST, R.drawable.divider_white_ef_1px, 0));
        mSearchRv.setLayoutManager(new LinearLayoutManager(HomeSearch_Activity.this, LinearLayoutManager.VERTICAL, false));
        mSearchRv.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                int type = data.get(position).getType();
                if (type == 1) {
                    Intent intent = new Intent(HomeSearch_Activity.this, WebViewActivity.class);
                    int did = data.get(position).getDid();
                    intent.putExtra("toolbar_tv", "医生主页");
                    intent.putExtra("url", ApiService.H5_URL_HOSPITALD + did + "&Sources=3");

                    //需要用医生did
                    int doctor_id = data.get(position).getDid();
                    intent.putExtra("doctor_id", doctor_id);
                    //把医生名字传过去
                    intent.putExtra("doctorname", data.get(position).getTrue_name());
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(HomeSearch_Activity.this, Hospitallisting_Activity.class);
                    int hid = data.get(position).getHid();
                    intent.putExtra("hid", hid);
                    String hospital_name = data.get(position).getHospital_name();
                    intent.putExtra("title", hospital_name);
                    startActivity(intent);
                }
            }
        });
    }


    /**
     * 文本框搜索医院或者医生
     */
    private void setmSearch(Map<String, String> map, final boolean flag) {
        RxUtils.getInstance().retrofit.create(ApiService.class).postHomeHomelist(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<HomeHomelist_Info>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(HomeHomelist_Info info) {
                        Logger.e("首页搜搜" + info.toString());

                        if (info.getCode() == 1) {
                            llCenterBg.setVisibility(View.GONE);
                            mSearchRr.setVisibility(View.GONE);
                            if (flag) {
                                data.clear();
                            }

                            if (null != info.getData() && info.getData().size() > 0) {
                                data.addAll(info.getData());
                            }
                            adapter.notifyDataSetChanged();
                        } else {
                            mSearchRr.setVisibility(View.GONE);
                            llCenterBg.setVisibility(View.VISIBLE);
                        }
                    }


                });
        try {
            //因为网络请求在子线程，所以不能让宿主线程过早的结束。
            Thread.sleep(100);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
    }


    /**
     * 搜索精心推荐
     */
    @Override
    public void initData() {
        initAdapter();
        initPost();


    }

    private void initPost() {
        OkHttp3Utlis.getIntance().postOkhttp(ApiService.BASE_URL + "/mobile/common/recommend", null, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                Logger.e("精心推荐" + result);
                Gson gson = new Gson();
                final Recommend_Info info = gson.fromJson(result, Recommend_Info.class);
                final List<Recommend_Info.DataBean> data = info.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        final LayoutInflater mInflater = LayoutInflater.from(HomeSearch_Activity.this);

                        mSearchFlow.setAdapter(new TagAdapter<Recommend_Info.DataBean>(data) {
                            @Override
                            public View getView(FlowLayout parent, final int position, final Recommend_Info.DataBean s) {
                                TextView tv = (TextView) mInflater.inflate(R.layout.item_flow_search,
                                        mSearchFlow, false);
                                tv.setText(s.getHospital_name());

                                return tv;
                            }
                        });
                        mSearchFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
                            @Override
                            public boolean onTagClick(View view, int position, FlowLayout parent) {
                                Intent intent = new Intent(HomeSearch_Activity.this, Hospitallisting_Activity.class);
                                int hid = data.get(position).getHid();
                                intent.putExtra("hid", hid);
                                String hospital_name = data.get(position).getHospital_name();
                                intent.putExtra("title", hospital_name);
                                startActivity(intent);
                                return true;
                            }
                        });

                    }

                });
            }
        });
    }

    /**
     * 监听输入框的变化
     */
    private void initTagFlowLayout() {
        mSearchInt.addTextChangedListener(new TextWatcher() {


            private CharSequence temp;

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //                mSearchClean.setVisibility(View.GONE);
                mSearchRv.setVisibility(View.GONE);

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //                if (s == null) {
                //                    mSearchRr.setVisibility(FindView.VISIBLE);
                //                    mSearchClean.setVisibility(FindView.GONE);
                //
                //                } else {
                //                    mSearchRv.setVisibility(FindView.VISIBLE);
                //                    mSearchClean.setVisibility(FindView.VISIBLE);
                //
                //                }
                temp = s;
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (temp.length() >= 1) {
                    mSearchRv.setVisibility(View.VISIBLE);

                } else {
                    mSearchRr.setVisibility(View.GONE);

                    data.clear();
                    adapter.notifyDataSetChanged();

                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        initRuanjianpan();
    }

    /**
     * 自动弹出键盘输入框
     */
    private void initRuanjianpan() {
        mSearchInt.setFocusable(true);
        mSearchInt.setFocusableInTouchMode(true);
        mSearchInt.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(mSearchInt, 0);
                           }
                       },
                200);
    }

    @OnClick({R.id.mSearch_int, R.id.mSearch_clean, R.id.mSearch_sousuo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.mSearch_int:
                //                if (!TextUtils.isEmpty(request)) {
                //                    mSearchClean.setVisibility(FindView.VISIBLE);
                //                }
                break;
            case R.id.mSearch_clean:
                mSearchInt.setText("");
                break;
            case R.id.mSearch_sousuo:
                mSearchRv.setVisibility(View.VISIBLE);
                request = mSearchInt.getText().toString().trim();
                Map<String, String> map = new TreeMap<>();
                map.put("name", request);
                map.put("sign", Md5Util2.createSign(map));
                setmSearch(map, true);
                break;
        }
    }


}
